﻿namespace Frameworks
{
    using System;
    using System.IO;
    using UnityEngine;

    internal class LoggerFile : IDisposable
    {
        private StreamWriter _logFileWriter;
        private bool _includeCallStacks;

        public LoggerFile(string filename, bool includeCallStacks = true)
        {
            _includeCallStacks = includeCallStacks;
            var fileLogPath = Path.Combine(Application.persistentDataPath, filename);
            Debug.Log("Initialising file logging to " + fileLogPath);

            _logFileWriter = new StreamWriter(fileLogPath, false);
            _logFileWriter.AutoFlush = true;
        }

        public void Dispose()
        {
            _logFileWriter.Close();
            _logFileWriter.Dispose();
        }

        public void Log(LogInfo logInfo)
        {
            lock (this)
            {
                _logFileWriter.WriteLine(logInfo.Message);

                if (_includeCallStacks && logInfo.Callstack.Count > 0)
                {
                    foreach (var frame in logInfo.Callstack)
                    {
                        _logFileWriter.WriteLine(frame.FormattedMethodNameWithFileName);
                    }
                    _logFileWriter.WriteLine();
                }
            }
        }
    }
}
